package com.beep.erp.common.widget.popwindow;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.beep.erp.R;
import com.beep.erp.common.utils.DateUtil;
import com.beep.erp.common.widget.wheel.widget.OnWheelScrollListener;
import com.beep.erp.common.widget.wheel.widget.WheelView;
import com.beep.erp.common.widget.wheel.widget.adapters.AbstractWheelTextAdapter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jolly on 2018/8/31
 */
public class SelectDatePop extends PopupWindow {
    private Context context;
    private String year, month, day;
    private String mTitle = "";
    private List<Map<String, Object>> yearList;//年 月 日的数据
    private int yearIndex, monthIndex, dayIndex;
    private OnDateClickListener listener;

    private WheelView viewYear;//年控件
    private WheelView viewMonth;//月控件
    private WheelView viewDay;//日控件

    private Button takePhotoBtn, pickPhotoBtn, cancelBtn;
    private View mMenuView;

    public SelectDatePop(final Context context, View view, String title) {
        this.context = context;
        mTitle = title;
        getData();
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.dialog_select_date, null);
        // 设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        // 设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        // 设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.AnimBottom);
        // 实例化一个ColorDrawable颜色为半透明

        ColorDrawable dw = new ColorDrawable(0x00000000);
//        dw.setAlpha(6);
        // 设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        this.showAtLocation(view,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        /* 设置触摸外面时消失 */
        this.setOutsideTouchable(true);
        this.setTouchable(true);
        /* 设置点击menu以外其他地方以及返回键退出 */
//        this.setFocusable(false);
        this.backgroundAlpha((Activity) context, 0.8f);
        this.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha((Activity) context, 1f);
            }
        });
        this.update();

        TextView textView = (TextView) mMenuView.findViewById(R.id.dialogTitle);
        textView.setText(mTitle);
        // 设置监听
        Button dialog_bottom_ok = (Button) mMenuView.findViewById(R.id.dialog_bottom_ok);
        dialog_bottom_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String year = yearList.get(viewYear.getCurrentItem()).get("year") + "";
                    String month = ((Map) ((List) yearList.get(viewYear.getCurrentItem()).get("month")).get(viewMonth.getCurrentItem())).get("month") + "";
                    String day = ((List) ((Map) ((List) yearList.get(viewYear.getCurrentItem()).get("month")).get(viewMonth.getCurrentItem())).get("day")).get(viewDay.getCurrentItem()) + "";
                    String select = year + "-" + month + "-" + day;
                    String current = DateUtil.getCurDateStr();
                    /*try {
                        Date select1 = dateFormat.parse(select);
                        Date current1 = dateFormat.parse(current);
                        int j = select1.compareTo(current1);
                        if (j > 0) {
                            ToastUtil.showToastOnlyOne("选择日期不能大于当前日期");
                            return;
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }*/
                    listener.onclick(year,
                            month,
                            day);
                    dismiss();
                }
            }
        });


        TextView tv_anyTime = (TextView) mMenuView.findViewById(R.id.tv_anyTime);
        tv_anyTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onclick(null, null, null);
                }
                dismiss();
            }
        });
        Button button = (Button) mMenuView.findViewById(R.id.dialog_bottom_cancle);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        initYear();//初始化year控件


    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public static void backgroundAlpha(Activity context, float bgAlpha) {

        // WindowManager.LayoutParams lp = mContext.getWindow().getAttributes();
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha; // 0.0-1.0
        context.getWindow().setAttributes(lp);
    }

    public void initYear() {
        viewYear = (WheelView) mMenuView.findViewById(R.id.date);
        viewYear.setVisibleItems(24); // Number of items
        viewYear.setWheelBackground(R.drawable.wheel_bgbottom_holo);
        viewYear.setWheelForeground(R.drawable.wheel_valbottom_holo);
        viewYear.setShadowColor(0xFFFFFFFF, 0x88FFFFFF, 0x00FFFFFF);
        viewYear.setViewAdapter(new YearAdapter(context));
        //hour.setViewAdapter(new HourAdapter(context));
        viewYear.setCurrentItem(yearIndex);
        viewYear.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                initMonth();
            }
        });
        initMonth();
    }

    public void initMonth() {
        viewMonth = (WheelView) mMenuView.findViewById(R.id.hour);
        viewMonth.setVisibleItems(24); // Number of items
        viewMonth.setWheelBackground(R.drawable.wheel_bgbottom_holo);
        viewMonth.setWheelForeground(R.drawable.wheel_valbottom_holo);
        viewMonth.setShadowColor(0xFFFFFFFF, 0x88FFFFFF, 0x00FFFFFF);
        viewMonth.setViewAdapter(new MonthAdapter(this.context, (List) yearList.get(viewYear.getCurrentItem()).get("month")));
        viewMonth.setCurrentItem(monthIndex);
        viewMonth.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                initDay();
            }
        });

        initDay();
    }

    public void initDay() {
        viewDay = (WheelView) mMenuView.findViewById(R.id.minute);
        viewDay.setVisibleItems(24); // Number of items
        viewDay.setWheelBackground(R.drawable.wheel_bgbottom_holo);
        viewDay.setWheelForeground(R.drawable.wheel_valbottom_holo);
        viewDay.setShadowColor(0xFFFFFFFF, 0x88FFFFFF, 0x00FFFFFF);
        viewDay.setViewAdapter(new DayAdapter(this.context, (List) ((Map) ((List) yearList.get(viewYear.getCurrentItem()).get("month")).get(viewMonth.getCurrentItem())).get("day")));
        viewDay.setCurrentItem(dayIndex);
    }

    public void setOnClickOK(OnDateClickListener listener) {
        this.listener = listener;
    }

    public interface OnDateClickListener {
        public void onclick(String year, String month, String day);
    }

    //设置滚动的数据源
    public void getData() {
        Calendar a = Calendar.getInstance();
        yearList = new ArrayList<Map<String, Object>>();
        int month_all = 12;
        int day_all = 31;
        int yearCurrent = a.get(Calendar.YEAR);
        int monthCurrent = a.get(a.MONTH) + 1;
        int dayCurrent = a.get(a.DATE);
        yearIndex = yearCurrent - 1900;//当前年份在列表中下标
        monthIndex = monthCurrent - 1;//当前月份在列表中下标
        dayIndex = dayCurrent - 1;//当前天在列表中下标
        for (int i_year = 1900; i_year < yearCurrent + 30; i_year++) {//年循环
            if (i_year == yearCurrent) {//判断是否是当前年份
                month_all = monthCurrent;
            } else {
                month_all = 1;
            }
            ArrayList<Map<String, Object>> monthList = new ArrayList<Map<String, Object>>();
            for (int i_month = 1; i_month < 13; i_month++) {//月循环
                switch (i_month) {
                    case 1:
                        day_all = 31;
                        break;
                    case 2:
                        if (isLeapYear(i_year)) {//判读是否是闰月
                            day_all = 29;
                        } else {
                            day_all = 28;
                        }
                        break;
                    case 3:
                        day_all = 31;
                        break;
                    case 4:
                        day_all = 30;
                        break;
                    case 5:
                        day_all = 31;
                        break;
                    case 6:
                        day_all = 30;
                        break;
                    case 7:
                        day_all = 31;
                        break;
                    case 8:
                        day_all = 31;
                        break;
                    case 9:
                        day_all = 30;
                        break;
                    case 10:
                        day_all = 31;
                        break;
                    case 11:
                        day_all = 30;
                        break;
                    case 12:
                        day_all = 31;
                        break;
                }
                int tDay = 1;
                if (i_year == yearCurrent && i_month == month_all) {
                    tDay = dayCurrent;
                } else {
                    tDay = 1;
                }
                ArrayList<String> dayList = new ArrayList<String>();
                for (int i_day = 1; i_day < day_all + 1; i_day++) {//日循环
                    if (i_day < 10) {
                        dayList.add("0" + i_day);//增加日的数据
                    } else {
                        dayList.add(i_day + "");//增加日的数据
                    }

                }
                HashMap<String, Object> monthMap = new HashMap<String, Object>();
                if (i_month < 10) {
                    monthMap.put("month", "0" + i_month);
                } else {
                    monthMap.put("month", i_month + "");
                }
                monthMap.put("day", dayList);
                monthList.add(monthMap);//增加月数据
            }
            HashMap<String, Object> yearMap = new HashMap<String, Object>();
            yearMap.put("year", i_year + "");
            yearMap.put("month", monthList);
            yearList.add(yearMap);//增加年数据
        }
    }

    //判断是否是闰年
    public static boolean isLeapYear(int year) {
        if ((year % 400) == 0)
            return true;
        else if ((year % 4) == 0) {
            if ((year % 100) == 0)
                return false;
            else
                return true;
        } else
            return false;
    }


    //年适配器
    public class YearAdapter extends AbstractWheelTextAdapter {
        // City names
        //final String cities[] = new String[] { "00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23" };

        /**
         * Constructor
         */
        protected YearAdapter(Context context) {
            super(context, R.layout.times_item_holo, AbstractWheelTextAdapter.NO_RESOURCE);
            setItemTextResource(R.id.time);
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
//            TextView time = (TextView) view.findViewById(R.id.time);
//            if(viewYear.getCurrentItem() == index){
//                time.setTextSize(18);
//            }else {
//                time.setTextSize(14);
//            }
            return view;
        }

        public int getItemsCount() {
            return yearList.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return yearList.get(index).get("year") + "";
        }
    }

    //月适配器
    public class MonthAdapter extends AbstractWheelTextAdapter {

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        protected MonthAdapter(Context context, List<Map<String, Object>> list) {
            super(context, R.layout.times_item_holo, AbstractWheelTextAdapter.NO_RESOURCE);
            setItemTextResource(R.id.time);
            this.list = list;
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
//            TextView time = (TextView) view.findViewById(R.id.time);
//            if(viewMonth.getCurrentItem() == index){
//                time.setTextSize(18);
//            }else {
//                time.setTextSize(14);
//            }
            return view;
        }

        public int getItemsCount() {
            return list.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return list.get(index).get("month") + "";
        }
    }

    //日适配器
    public class DayAdapter extends AbstractWheelTextAdapter {

        List<String> list = new ArrayList<String>();

        protected DayAdapter(Context context, List<String> list) {
            super(context, R.layout.times_item_holo, AbstractWheelTextAdapter.NO_RESOURCE);
            setItemTextResource(R.id.time);
            this.list = list;
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            return view;
        }

        public int getItemsCount() {
            return list.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return list.get(index);
        }
    }
}
